package TestPaperSystem.controller;


import TestPaperSystem.Dto.UserLoginDto;
import TestPaperSystem.Dto.UserVO;
import TestPaperSystem.entity.User;
import TestPaperSystem.service.UserService;
import TestPaperSystem.utils.R;
import TestPaperSystem.utils.RedisUtils;
import TestPaperSystem.utils.ResponseUtils_R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xwj
 * @since 2023-03-25
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userServiceImpl;

    @PostMapping("/login")
    public R login(@RequestBody User user){
        UserLoginDto userLoginDto = new UserLoginDto();
        try{
            userLoginDto = userServiceImpl.getUser(user);
        }catch (Exception e){
            return ResponseUtils_R.error(e.getMessage());
        }
        return ResponseUtils_R.success(userLoginDto);
    }

    @PostMapping("/info")
    public R getInfo(@RequestHeader("token") String token){
        UserLoginDto user = new UserLoginDto();
        try{
            user = (UserLoginDto) RedisUtils.redis.opsForValue().get(token);
        }catch (Exception e){
            return ResponseUtils_R.error("未找到信息");
        }

        return ResponseUtils_R.success(user);
    }

    @PostMapping("/register")
    @Transactional
    public R register(@RequestBody UserVO user) throws Exception{
        UserLoginDto userLoginDto = null;
        try {
            userLoginDto = userServiceImpl.saveUser(user);
        }catch (Exception e){
            return ResponseUtils_R.error(e.getMessage());
        }
        return ResponseUtils_R.success(userLoginDto);
    }

    @PostMapping("/resetPass")
    public R reSetPass(@RequestBody UserVO resetForm){

        UserLoginDto userLoginDto = null;
        try {
            userLoginDto = userServiceImpl.updateUserPass(resetForm);
        }catch (Exception e){
            return ResponseUtils_R.error(e.getMessage());
        }
        return ResponseUtils_R.success(userLoginDto);
    }


    @PostMapping("/loginOut")
    public R loginOut(@RequestHeader("token") String token){
        try{
            RedisUtils.redis.delete(token);
        }catch (Exception e){
            return ResponseUtils_R.error("会话过期");
        }
        return ResponseUtils_R.success("注销成功");
    }


    @GetMapping("/code/{userName}")
    public R getCode(@PathVariable String userName)throws Exception{
        return ResponseUtils_R.success(userServiceImpl.getCode(userName));
    }
}

